//dom加载完成后执行的js
;$(function(){

	//全选的实现
	$(".check-all").click(function(){
		$(".ids").prop("checked", this.checked);
	});
	$(".ids").click(function(){
		var option = $(".ids");
		option.each(function(i){
			if(!this.checked){
				$(".check-all").prop("checked", false);
				return false;
			}else{
				$(".check-all").prop("checked", true);
			}
		});
	});

    //ajax get请求
    $('.ajax-get').click(function(){
        var target;
        var that = this;
        if ( $(this).hasClass('confirm') ) {
            if(!confirm('确认要执行该操作吗?')){
                return false;
            }
        }
        if ( (target = $(this).attr('href')) || (target = $(this).attr('url')) ) {
            $.get(target).success(function(data){
                if (data.status==1) {
                    if (data.url) {
                        updateAlert(data.info + ' 页面即将自动跳转~','alert-success');
                    }else{
                        updateAlert(data.info,'alert-success');
                    }
                    setTimeout(function(){
                        if (data.url) {
                            location.href=data.url;
                        }else if( $(that).hasClass('no-refresh')){
                            $('#top-alert').find('button').click();
                        }else{
                            location.reload();
                        }
                    },1500);
                }else{
                    updateAlert(data.info);
                    setTimeout(function(){
                        if (data.url) {
                            location.href=data.url;
                        }else{
                            $('#top-alert').find('button').click();
                        }
                    },1500);
                }
            });

        }
        return false;
    });

    //ajax post submit请求
    $('.ajax-post').click(function(){
        var target,query,form;
        var target_form = $(this).attr('target-form');
        var that = this;
        var nead_confirm=false;
        if( ($(this).attr('type')=='submit') || (target = $(this).attr('href')) || (target = $(this).attr('url')) ){
            form = $('.'+target_form);

            if ($(this).attr('hide-data') === 'true'){//无数据时也可以使用的功能
            	form = $('.hide-data');
            	query = form.serialize();
            }else if (form.get(0)==undefined){
            	return false;
            }else if ( form.get(0).nodeName=='FORM' ){
                if ( $(this).hasClass('confirm') ) {
                    if(!confirm('确认要执行该操作吗?')){
                        return false;
                    }
                }
                if($(this).attr('url') !== undefined){
                	target = $(this).attr('url');
                }else{
                	target = form.get(0).action;
                }
                query = form.serialize();
            }else if( form.get(0).nodeName=='INPUT' || form.get(0).nodeName=='SELECT' || form.get(0).nodeName=='TEXTAREA') {
                form.each(function(k,v){
                    if(v.type=='checkbox' && v.checked==true){
                        nead_confirm = true;
                    }
                })
                if ( nead_confirm && $(this).hasClass('confirm') ) {
                    if(!confirm('确认要执行该操作吗?')){
                        return false;
                    }
                }
                query = form.serialize();
            }else{
                if ( $(this).hasClass('confirm') ) {
                    if(!confirm('确认要执行该操作吗?')){
                        return false;
                    }
                }
                query = form.find('input,select,textarea').serialize();
            }
            $(that).addClass('disabled').attr('autocomplete','off').prop('disabled',true);
            $.post(target,query).success(function(data){
                if (data.status==1) {
                    if (data.url) {
                        updateAlert(data.info + ' 页面即将自动跳转~','alert-success');
                    }else{
                        updateAlert(data.info ,'alert-success');
                    }
                    setTimeout(function(){
                    	$(that).removeClass('disabled').prop('disabled',false);
                        if (data.url) {
                            location.href=data.url;
                        }else if( $(that).hasClass('no-refresh')){
                            $('#top-alert').find('button').click();
                        }else{
                            location.reload();
                        }
                    },1500);
                }else{
                    updateAlert(data.info);
                    setTimeout(function(){
                    	$(that).removeClass('disabled').prop('disabled',false);
                        if (data.url) {
                            location.href=data.url;
                        }else{
                            $('#top-alert').find('button').click();
                        }
                    },1500);
                }
            });
        }
        return false;
    });

	/**顶部警告栏*/
	var content = $('#main');
	var top_alert = $('#top-alert');
	top_alert.find('.close').on('click', function () {
		top_alert.removeClass('block').slideUp(200);
		// content.animate({paddingTop:'-=55'},200);
	});

    window.updateAlert = function (text,c) {
		text = text||'default';
		c = c||false;
		if ( text!='default' ) {
            top_alert.find('.alert-content').text(text);
			if (top_alert.hasClass('block')) {
			} else {
				top_alert.addClass('block').slideDown(200);
				// content.animate({paddingTop:'+=55'},200);
			}
		} else {
			if (top_alert.hasClass('block')) {
				top_alert.removeClass('block').slideUp(200);
				// content.animate({paddingTop:'-=55'},200);
			}
		}
		if ( c!=false ) {
            top_alert.removeClass('alert-error alert-warn alert-info alert-success').addClass(c);
		}
	};

    //按钮组
    (function(){
        //按钮组(鼠标悬浮显示)
        $(".btn-group").mouseenter(function(){
            var userMenu = $(this).children(".dropdown ");
            var icon = $(this).find(".btn i");
            icon.addClass("btn-arrowup").removeClass("btn-arrowdown");
            userMenu.show();
            clearTimeout(userMenu.data("timeout"));
        }).mouseleave(function(){
            var userMenu = $(this).children(".dropdown");
            var icon = $(this).find(".btn i");
            icon.removeClass("btn-arrowup").addClass("btn-arrowdown");
            userMenu.data("timeout") && clearTimeout(userMenu.data("timeout"));
            userMenu.data("timeout", setTimeout(function(){userMenu.hide()}, 100));
        });

        //按钮组(鼠标点击显示)
        // $(".btn-group-click .btn").click(function(){
        //     var userMenu = $(this).next(".dropdown ");
        //     var icon = $(this).find("i");
        //     icon.toggleClass("btn-arrowup");
        //     userMenu.toggleClass("block");
        // });
        $(".btn-group-click .btn").click(function(e){
            if ($(this).next(".dropdown").is(":hidden")) {
                $(this).next(".dropdown").show();
                $(this).find("i").addClass("btn-arrowup");
                e.stopPropagation();
            }else{
                $(this).find("i").removeClass("btn-arrowup");
            }
        })
        $(".dropdown").click(function(e) {
            e.stopPropagation();
        });
        $(document).click(function() {
            $(".dropdown").hide();
            $(".btn-group-click .btn").find("i").removeClass("btn-arrowup");
        });
    })();

    // 独立域表单获取焦点样式
    $(".text").focus(function(){
        $(this).addClass("focus");
    }).blur(function(){
        $(this).removeClass('focus');
    });
    $("textarea").focus(function(){
        $(this).closest(".textarea").addClass("focus");
    }).blur(function(){
        $(this).closest(".textarea").removeClass("focus");
    });
});

/* 上传图片预览弹出层 */

//标签页切换(无下一步)
function showTab() {
    $(".tab-nav li").click(function(){
        var self = $(this), target = self.data("tab");
        self.addClass("current").siblings(".current").removeClass("current");
        window.location.hash = "#" + target.substr(3);
        $(".tab-pane.in").removeClass("in");
        $("." + target).addClass("in");
    }).filter("[data-tab=tab" + window.location.hash.substr(1) + "]").click();
}

//标签页切换(有下一步)
function nextTab() {
     $(".tab-nav li").click(function(){
        var self = $(this), target = self.data("tab");
        self.addClass("current").siblings(".current").removeClass("current");
        window.location.hash = "#" + target.substr(3);
        $(".tab-pane.in").removeClass("in");
        $("." + target).addClass("in");
        showBtn();
    }).filter("[data-tab=tab" + window.location.hash.substr(1) + "]").click();

    $("#submit-next").click(function(){
        $(".tab-nav li.current").next().click();
        showBtn();
    });
}

// 下一步按钮切换
function showBtn() {
    var lastTabItem = $(".tab-nav li:last");
    if( lastTabItem.hasClass("current") ) {
        $("#submit").removeClass("hidden");
        $("#submit-next").addClass("hidden");
    } else {
        $("#submit").addClass("hidden");
        $("#submit-next").removeClass("hidden");
    }
}

//导航高亮
function highlight_subnav(url){
    $('.side-sub-menu').find('a[href="'+url+'"]').closest('li').addClass('current');
}

/**
 * ajax请求
 */
function ajaxRequest(url, params, option)
{
	if(option == null) {
		option = new Array();
	}
	
	if(params == null) {
		params = new Array();
	}

	var ds = null;
	
	$.ajax({
		url: url,
		type:option['type'] ? option['type'] : 'post',
		data:params,
		dataType:option['dataType'] ? option['dataType'] : 'json',
		async:(option['async'] === false) ? option['async'] : true,
		cache: false,
		success: function(data){
			//如果是同步请求，返回请求结果
			if(option['async'] === false) {
				ds = data;
				return;
			}
			
			//异步请求必需传入请求结果处理函数
			if(option['func'] == null) {
				alert('请传入处理函数');
				return;
			}
			
			option.func(data);
		},
	});
	
	//如果是同步请求，则返回请求结果
	if(option['async'] == false) {
		return ds;
	}
}

/**
 * 倒计时器
 * @param param
 */
function timer(param)
{
	var leftTime = param['leftTime'];
	//如果没有传入倒计时时间则返回false；
	if(leftTime == null) {
		return false;
	}
	
	//如果没有传入处理函数，则反回false；
	if(param['func'] == null) {
		return false;
	}
	
	if(leftTime <= 0) {
		param.func('00天00时00分00秒');
		return;
	}
	
	var startTime = parseInt(new Date().getTime()/1000);
	var day = Math.floor(leftTime/86400);
	var hour = Math.floor((leftTime - day*86400)/3600);
	var minute = Math.floor((leftTime - day*86400 - hour*3600)/60);
	var second = leftTime - day*86400 - hour*3600 - minute*60;
	var tmp = 0;
	
	var timeStr = function(day, hour, minute, second) {
		var ds = '天';
		var hs = '时';
		var ms = '分';
		var ss = '秒';
		
		if(day < 10) {
			ds = '0' + day + ds;
		} else {
			ds = day + ds;
		}
		
		if(hour < 10) {
			hs = '0' + hour + hs;
		} else {
			hs = hour + hs;
		}
		
		if(minute < 10) {
			ms = '0' + minute + ms;
		} else {
			ms = minute + ms;
		}
		
		if(second < 10) {
			ss = '0' + second + ss;
		} else {
			ss = second + ss;
		}
		
		return ds + hs + ms + ss;
	}
	
	param.func(timeStr(day, hour, minute, second));
	
	var t = setInterval(function(){
		if(second > 0) {
			second--;
		} else if(minute > 0) {
			minute--;
		} else if(hour > 0) {
			hour--;
		} else if(day > 0) {
			day--;
		} else {
			clearInterval(t);
			return;
		}
		
		tmp = startTime - parseInt(new Date().getTime()/1000) + leftTime;
		day = Math.floor(tmp/86400);
		hour = Math.floor((tmp - day*86400)/3600);
		minute = Math.floor((tmp - day*86400 - hour*3600)/60);
		second = tmp - day*86400 - hour*3600 - minute*60;
		
		//执行回调函数
		param.func(timeStr(day, hour, minute, second));
		
	}, 1000);
}

//上传文件
function upload(container, data, option)
{
	if(!option.buttonText) option.buttonText = '上传文件';
	if(!option.onUploadStart) option.onUploadStart = function(){};
	if(!option.onUploadSuccess) option.onUploadSuccess = function(){};
	
	if(!option.uploader) {
		alert('请设置服务器端上传文件处理脚本');
		return;
	}
	
	if(!option.fileTypeExts) {
		alert('请设置允许上传的文件类型');
		return;
	}
	
	if(!option.fileSizeLimit) {
		alert('请设置允许上传的文件大小');
		return;
	}
	
	if(!option.fileTypeExts) {
		alert('请设置允许上传的文件类型');
		return;
	}
	
	$(container).uploadify({
        "height"          : 30,
        "swf"             : option.swf,
        "fileObjName"     : "download",
        "formData"		  : data,
        "buttonText"      : option.buttonText,
        "height"    		   : "25",
        "fileTypeExts"	  : option.fileTypeExts,
        "fileSizeLimit"	  : option.fileSizeLimit,
        "uploader"        : option.uploader,
        "width"              : 120,
        "multi"				  : false,
        'removeTimeout'	  : 1,
        'onFallback' : function() {
            alert('未检测到兼容版本的Flash.');
        },
        "onUploadStart":option.onUploadStart,
        "onUploadSuccess" : option.onUploadSuccess,
    });
}

/**
 * 信息提示框
 * @param $msg 提示信息
 * @param $type 信息类型 alert-success,alert-error,alert-warn
 */
function alertDialog($msg, $type, $time)
{
	$time = $time ? $time : 1500;
	updateAlert($msg, $type);
	setTimeout(function(){
		$(".close").click();
	}, $time);
}

/**
 * 信息提示框
 * @param data
 * @param option
 */
function jsonDataDialog(data, option)
{
	if(data) {
		if(data.error == 0) {
			alertDialog(data.msg, 'alert-success');
			if(option && option.success) option.success(data.msg);
		} else {
			alertDialog(data.msg, 'alert-error');
			if(option && option.error) option.success(data.msg);
		}
	} else {
		alertDialog('操作失败', 'alert-error');
	}
}

/**
 * 
 */
function kinder()
{
	KindEditor.ready(function(K) {
		window.editor = K.create('textarea[class="kind-editor"]', {
			//allowFileManager : false
			allowFileManager : true,
			uploadJson:"{:U('File/kinderUpload')}",
			minWidth:900,
			minHeight:300,
			afterBlur: function(){this.sync();},
		});
	});
}

function load_html(obj){
    if(typeof obj != 'object')  return false;
    if( !obj.url )  return false;
    var _html = '<div class="modal">' +
        '<div class="modal-dialog">' +
        '<div class="modal-content"> ' +
        (obj.hasOwnProperty('title') ? ('<div class="modal-header">' +
        '<button type="button" class="close modal-close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>' +
        '<h4 class="modal-title" id="gridModalLabel">'+obj.title+'</h4>' +
        '</div>' ) : '')+
        '<div class="modal-body"></div>' +
        (obj.hasOwnProperty('button') && obj.button ? ('<div class="modal-footer">' +
        '<button type="button" class="btn btn-return modal-close" data-dismiss="modal" aria-label="Close">取消</button>' +
        '<button type="button" class="btn btn-primary submit-btn modal-submit">确定</button>' +
        '</div>' ) : '')+
        '</div>' +
        '</div>' +
        '</div>';
    $('body').addClass('modal-open').append(_html);

    $('.modal, .modal-close').on('click', function(){
        close_modal();
    });
    $('.modal-content').on('click', function(event){
        event.stopPropagation();
    });
    $.get(
        obj.url,function(html){
            $('.modal .modal-body').html(html);
            return false;
        }
    );
    return false;
}

function close_modal(){
    $('.modal').remove();
    $('body').removeClass('modal-open');
}
